import { requestInterceptor, responseInterceptor, errorInterceptor } from './interceptor'
import { useUserStore } from '@/store/user'
import config from '@/config'

// 封装uni.request为Promise形式，便于API调用
const BASE_URL = config.baseURL; // 从配置文件获取API地址

import { showLoading, hideLoading } from './loading.js'

/**
 * 显示全局loading
 */
function showGlobalLoading() {
  showLoading({
    title: '加载中...',
    mask: true
  })
}
/**
 * 隐藏全局loading
 */
function hideGlobalLoading() {
  hideLoading()
}

/**
 * 刷新token（双token机制）
 * @returns {Promise<{accessToken:string,refreshToken:string}>}
 */
function refreshToken() {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore();
    uni.request({
      url: BASE_URL + '/wechat/refreshToken',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        refreshToken: userStore.refreshToken
      },
      timeout: 5000, // 5秒超时
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === '0') {
          const { accessToken, refreshToken } = res.data.data;
          userStore.updateToken({ accessToken, refreshToken });
          resolve({ accessToken, refreshToken });
        } else {
          reject(res.data);
        }
      },
      fail: reject
    });
  });
}

/**
 * 执行单次请求的内部方法
 * @param {Object} config - 请求配置
 * @param {string} fullUrl - 完整URL
 * @returns {Promise}
 */
function makeRequest(config, fullUrl) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: fullUrl,
      method: config.method || 'GET',
      data: config.data || config.params || {},
      header: config.header,
      timeout: 5000, // 5秒超时，与loading超时时间保持一致
      success: (res) => {
        try {
          const data = responseInterceptor(res);
          resolve(data);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        errorInterceptor(err);
        reject(err);
      }
    });
  });
}

/**
 * 带重试机制的请求方法
 * @param {Object} config - 请求配置
 * @param {string} fullUrl - 完整URL
 * @returns {Promise}
 */
async function makeRequestWithRetry(config, fullUrl) {
  try {
    return await makeRequest(config, fullUrl);
  } catch (error) {
    // 如果是token失效错误，尝试刷新token后重试
    if (error.statusCode === 200 && error.data && error.data.code === '8001') {
      try {
        await refreshToken();
        // 更新token后重试
        config.header['token'] = useUserStore().accessToken;
        return await makeRequest(config, fullUrl);
      } catch (refreshError) {
        // 刷新失败，跳转登录
        useUserStore().logout();
        uni.redirectTo({ url: '/pages/login/index' });
        throw refreshError;
      }
    }
    throw error;
  }
}

/**
 * 统一请求方法，集成全局loading和自动刷新token（双token机制）
 * @param {Object} options - 请求配置
 * @returns {Promise}
 */
export default function request(options) {
  showGlobalLoading();
  
  return new Promise(async (resolve, reject) => {
    try {
      const userStore = useUserStore();
      // 使用请求拦截器
      const config = requestInterceptor(options);
      
      // 添加accessToken
      if (!config.header) config.header = {};
      if (userStore.accessToken) {
        config.header['token'] = userStore.accessToken;
      }
      
      const fullUrl = config.url.startsWith('http') ? config.url : `${BASE_URL}${config.url}`;
      
      // 执行请求（包含重试逻辑）
      const result = await makeRequestWithRetry(config, fullUrl);
      resolve(result);
      
    } catch (error) {
      reject(error);
    } finally {
      // 确保loading总是被隐藏
      hideGlobalLoading();
    }
  });
}